package edu.ilstu.mind.ise.ccp.impl.queued;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import edu.ilstu.mind.ise.ccp.message.Message;
import edu.ilstu.mind.ise.ccp.module.Module;

class QueuedModuleThread extends Thread {
	private final Module module;
	private final BlockingQueue<Message> messageQueue = new LinkedBlockingQueue<Message>();
	
	public QueuedModuleThread(Module module) {
		this.module = module;
	}
	
	public void enqueue(Message message) {
		try {
			messageQueue.put(message);
		} catch (InterruptedException e) {
			// translate to runtime exception. this shouldn't happen.
			throw new RuntimeException(e);
		}
	}
	
	public Module getModule() {
		return module;
	}
	
	@Override
	public void run() {
		try {
			while(true) {
				Message message = messageQueue.take();
				if(message != null) {
					module.processMessage(message);
				}
			}
		} catch (InterruptedException e) {
			// exit the thread
		}
	}
}
